var express = require('express')
var router = express.Router()
const { userModel,bandsSModel } = require('../module/cyd_db')
var jwt = require('jsonwebtoken')

var aes = require("../untils/aes.js")
var rsa = require("../untils/rsa.js")
var key = require("../untils/key.js")
var utils = require("../untils/md5")


router.get('/aaa', async (req, res) => {

    res.send(
        200
    )

})

// 手机号登录/注册
router.post('/pwdlogin', async (req, res) => {
    // 请求头获取前端aes秘钥
    let skey = req.headers.skey
    // 用私钥解密 获取aeskey
    let aeskey = rsa.jiemi(skey, key.privateKey)

    let data = JSON.parse(aes.jiemi(req.body.data, aeskey))

    let pwd = data.pwd
    let user = await userModel.find({ mobile: data.mobile })

    if (user[0]) {

        let access_token = "Bearer " + jwt.sign({ username: user.username, password: user.password }, 'token', { expiresIn: 60 * 60 * 24 });
        let refresh_token = "Bearer " + jwt.sign({ username: user.username, password: user.password }, 'token', { expiresIn: '24h' });

        let timestamp = user[0].key

        let user_ticket_client = utils.md5(utils.md5(utils.md5(pwd + utils.md5(data.mobile))) + timestamp) //客户端密码

        if (user[0].password == user_ticket_client) {
            let userdata = aes.jiami(JSON.stringify({
                code: 200,
                msg: '登录成功',
                userInfo: user[0],
                access_token,
                refresh_token
            }), aeskey) + ''
            res.send(
                userdata
            )
        } else {
            let userdata = aes.jiami(JSON.stringify({
                code: 201,
                msg: '用户名或密码错误',
            }), aeskey) + ''
            res.send(
                userdata
            )
        }


    } else {
        let userdata = aes.jiami(JSON.stringify({
            code: 201,
            msg: '用户名或密码错误',
        }), aeskey) + ''
        res.send(
            userdata
        )

    }

    return

})

// 微信登录
router.post('/wxlogin', async (req, res) => {

    let openid = req.body.openid
    let username = req.body.nickName

    let user = await userModel.find({ openid: openid })
    console.log(user);
    if (user[0]) {
        if (user[0].mobile) {
            let access_token = "Bearer " + jwt.sign({ username: user.username, password: user.password }, 'token', { expiresIn: 60 * 60 * 24 });
            let refresh_token = "Bearer " + jwt.sign({ username: user.username, password: user.password }, 'token', { expiresIn: '24h' });
            res.send({
                code: 200,
                userInfo: user[0],
                msg: "登录成功",
                access_token,
                refresh_token
            })
        }

    } else {

        res.send({
            code: 201,
        })

    }
    return
})

// 添加用户(用户注册)
router.post('/regist', async (req, res) => {

    let mobile = req.body.mobile
    let openid = req.body.openid

    let user = await userModel.find({ mobile })

    if (user[0]) {
        res.send({
            code: 200,
            userInfo: user[0],
            msg: "改手机号已注册",

        })
        return
    } else {
        // 新建用户
        let username = "微信用户" + Math.floor(Math.random() * 10)

        let timestamp = Date.parse(new Date()) / 1000

        let pwd = '123456' //默认密码

        let user_ticket_client = utils.md5(utils.md5(utils.md5(pwd + utils.md5(mobile))) + timestamp) //微信登录默认密码


        await userModel.create({ username, mobile, openid, key: timestamp, password: user_ticket_client })
        let user = await userModel.find({ mobile })

        let access_token = "Bearer " + jwt.sign({ username: username, password: "123456" }, 'token', { expiresIn: 60 * 60 * 24 });
        let refresh_token = "Bearer " + jwt.sign({ username: username, password: "123456" }, 'token', { expiresIn: '24h' });

        res.send({
            code: 200,
            userInfo: user[0],
            msg: "登录成功",
            access_token,
            refresh_token
        })
        return
    }


})

// 请求当前用户车牌信息
router.get("/bands" , async (req , res)=>{

    let id = req.query.id

    let bands =await  bandsSModel.find({u_id : id})
    res.send({
        code : 200,
        data : bands
    })

})

// 添加车牌
router.post("/addbands",async (req,res)=>{
    

    let body = req.body
    await bandsSModel.create(body)
    res.send({
        code : 200
    })

})


module.exports = router;
